<template>
	<div class="system-user-dialog-container energy-from energy-dialog energy-tree">
		<el-dialog center align-center v-model="state.dialog.isShowDialog" width="769px" @close="resetData">
			<template #header="{ titleClass }">
				<div :class="titleClass">
					{{ state.dialog.isAssign ? '分配角色' : '权限详情' }}
				</div>
			</template>
			<el-form ref="userDialogFormRef" :model="state.ruleForm" :rules="state.rules" size="default" label-width="90px">
				<el-row :gutter="35">
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户姓名" prop="username">
							<el-input v-model="state.ruleForm.username" disabled placeholder="请输入用户姓名" clearable></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户类型">
							<el-radio-group v-model="state.ruleForm.userType" disabled>
								<el-radio :label="0">管理员 (不可删除)</el-radio>
								<el-radio :label="1">普通用户 (可删除)</el-radio>
							</el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户状态">
							<el-switch
								v-model="state.ruleForm.status"
								size="default"
								:active-value="0"
								:inactive-value="1"
								active-text="启用"
								inactive-text="禁用"
								inline-prompt
								style="--el-switch-on-color: #13ce66"
								disabled
							/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="用户角色" prop="roles">
							<el-select v-model="state.ruleForm.roles" multiple placeholder="请选择用户角色" style="width: 240px" :disabled="!state.dialog.isAssign">
								<el-option v-for="item in state.ruleForm.allRoleList" :key="item.id" :label="item.name" :value="item.id" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="用户权限">
							<el-tree
								ref="treeRef"
								:data="state.ruleForm.menuData"
								:props="state.ruleForm.menuProps"
								node-key="id"
								:default-checked-keys="state.ruleForm.defaultChecked"
								:default-expanded-keys="state.ruleForm.defaultChecked"
								show-checkbox
								check-strictly
								class="menu-data-tree"
								disabled
							/>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
			<div class="flex row-center mt10 mb10">
				<div class="btn3" @click="onCancel">
					<el-icon> <ele-Close /> </el-icon><span class="ml6">{{ state.dialog.isAssign ? '取 消' : '关 闭' }}</span>
				</div>
				<div class="btn1 ml10" @click="onSubmit()" v-if="state.dialog.isAssign">
					<el-icon> <ele-Check /> </el-icon><span class="ml6">保 存</span>
				</div>
			</div>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="assignRolesDialog">
import { reactive, ref, nextTick } from 'vue';
// import { useUserApi } from '/@/api/user/index'
import { useRoleApi } from '/@/api/role/index';
import { ElNotification } from 'element-plus';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);

// 定义变量内容
const userDialogFormRef = ref();
const state: any = reactive({
	ruleForm: {
		id: '', // 用户id
		username: '', // 用户姓名
		userType: 1, // 用户类型（0管理员，1普通用户）
		status: 0, // 	用户状态（0正常 1停用）
		roles: [], // 用户角色
		menuData: [], // 所有权限
		defaultChecked: [], // 默认选中的id集合
		allRoleList: [], // 所有角色
		menuProps: {
			children: 'childList',
			label: 'title',
			disabled: 'disabled',
		},
	},
	dialog: {
		isShowDialog: false,
		isAssign: true,
	},
	rules: {
		roles: [{ required: true, message: '请选择用户角色', trigger: 'blur' }],
	},
});

// 打开弹窗
const openDialog = (row: any, isAssign: boolean) => {
	state.dialog.isShowDialog = true;
	state.dialog.isAssign = isAssign;

	state.ruleForm.id = row.id;
	state.ruleForm.username = row.username;
	state.ruleForm.userType = row.userType;
	state.ruleForm.status = row.status;

	getAllRoleList();
	getUserRoleWithPermission(row.id);
};

// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 取消
const onCancel = () => {
	closeDialog();
};

// 表单清空
const resetData = () => {
	nextTick(() => {
		userDialogFormRef.value.resetFields();
		state.ruleForm.roles = [];
		state.ruleForm.menuData = [];
		state.ruleForm.defaultChecked = [];
	});
};

// 获取用户拥有的角色
const getUserRoleWithPermission = async (id: string) => {
	const { data } = await useRoleApi().getUserRoleList({ userId: id });
	data.roles.map((item: any) => state.ruleForm.roles.push(item.id));
	state.ruleForm.menuData = [...data.menus];

	let tileData: any = [];
	function changMenuData(data: []) {
		data.forEach((item: any) => {
			item.disabled = 1;
			tileData.push(item);
			if (item.childList && item.childList.length > 0) {
				changMenuData(item.childList);
			}
		});
	}
	changMenuData(data.menus);

	state.ruleForm.defaultChecked = [];
	tileData.map((item: any) => {
		if (item.selected == 1) {
			state.ruleForm.defaultChecked.push(item.id);
		}
	});
};

// 获取所有角色
const getAllRoleList = async () => {
	const { data } = await useRoleApi().getAllRoleList({
		pageNum: 1,
		pageSize: 100,
	});
	state.ruleForm.allRoleList = data.records;
};

// 分配角色
const doAssignRole = async () => {
	const data = await useRoleApi().assignRole({
		roleIds: state.ruleForm.roles,
		userId: state.ruleForm.id,
	});
	if (data.code == 200) {
		ElNotification({
			title: '提示',
			message: '分配角色成功',
			position: 'top-right',
			type: 'success',
		});
		emit('refresh');
	}
};

// 提交
const onSubmit = () => {
	userDialogFormRef.value.validate((valid: any) => {
		if (valid) {
			if (state.dialog.isAssign) {
				doAssignRole();
			}
		} else {
			ElNotification({
				title: '提示',
				message: '校验失败,请填写完整用户信息',
				position: 'top-right',
				type: 'error',
			});
		}
		closeDialog();
	});
};

// 暴露变量
defineExpose({
	openDialog,
});
</script>
<style scoped lang="scss"></style>
